/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.module.me

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_edit_info.*
import kotlinx.android.synthetic.main.include_header.*
import top.stime21.framework.extension.toActivity
import top.stime21.myneighbours.R
import top.stime21.myneighbours.api.ApiManager
import top.stime21.myneighbours.api.UploadManager
import top.stime21.myneighbours.base.io_main
import top.stime21.myneighbours.data.entity.User
import top.stime21.myneighbours.utils.ACache
import top.stime21.myneighbours.utils.ImageLoader
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

class EditInfoActivity : AppCompatActivity() {
    private var user: User? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_info)
        initData()
        initEvent()
    }

    private fun initEvent() {
        btn_avatar.setOnClickListener(l)
        btn_sign.setOnClickListener(l)
        btn_name.setOnClickListener(l)
        btn_gender.setOnClickListener(l)
    }

    private val l: View.OnClickListener = object : View.OnClickListener {
        override fun onClick(v: View?) {
            when (v) {
                btn_avatar ->getAvataFromAlbum()
                btn_sign ->toActivity<EditSignatureActivity>()
                btn_name ->toActivity<EditNameActivity>()
                btn_gender ->toActivity<EditGenderActivity>()
            }
        }
    }

    /**
     * 相簿取得图片，
     * 结果通过onActivityReslut返回
     */
    private fun getAvataFromAlbum() {
        val intent2 = Intent(Intent.ACTION_GET_CONTENT)
        intent2.type = "image/*"
        startActivityForResult(intent2, 2)
    }

    /**
     * 裁剪头像图片
     * 结果通过onActivityReslut返回
     *
     * @param uri
     */
    fun startPhotoZoom(uri: Uri?) {
        val intent = Intent("com.android.camera.action.CROP")
        intent.setDataAndType(uri, "image/*")
        intent.putExtra("aspectX", 1)//X方向上的比例
        intent.putExtra("aspectY", 1)//Y方向上的比例
        intent.putExtra("outputX", 300)//裁剪区的宽
        intent.putExtra("outputY", 300)//裁剪区的高
        intent.putExtra("crop", "true")//发送裁剪信号
        intent.putExtra("scale", true)//是否保留比例
        intent.putExtra("scaleUpIfNeeded", true)
        // intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true)//是否返回数据
        startActivityForResult(intent, 3)

    }

    protected override fun onActivityResult(requestCode: Int, resultCode: Int,
                                            data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                2 -> {
                    if (data == null) {
                        return
                    }
                    startPhotoZoom(data.data)
                }
                3 -> if (data != null) {
                    val extras = data.extras
                    if (extras != null) {
                        val bitmap = extras.getParcelable<Bitmap>("data")
                        val url = saveImage(bitmap)
                        val file = File(url)
                        UploadManager.ins().upload(file, "image/avatar/" + user!!.userId + "_" + System.currentTimeMillis() + ".png")
                                .subscribe({ s ->
                                    ApiManager.ins().dataApi.updateInfo("avatar", s, user!!.userId).io_main().subscribe({ result ->
                                        ACache.get(this@EditInfoActivity).put("user", user)
                                        ImageLoader().loadCircle("file://${url}", iv_avatar)
                                    }, { t ->
                                        Logger.e(t.toString())
                                    })
                                }, { t ->
                                    Logger.e(t.toString())
                                })
                    }
                }
                else -> {
                }
            }

        }
    }

    fun saveImage(bmp: Bitmap): String {
        val appDir = File(Environment.getExternalStorageDirectory(), "Avatar")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".png"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return file.absolutePath
    }


    private fun initData() {
        tv_title.setText("编辑信息")
        btn_back.setOnClickListener({finish()})
        user = ACache.get(this).getAsObject("user") as User
        if (user!!.avatar != null)
            ImageLoader().loadCircle(user!!.avatar, iv_avatar)
        tv_nickname.setText(user!!.nickName)
        im_gender.setImageResource(if (user!!.gender === 0) R.mipmap.sex_man else R.mipmap.sex_female)

    }

    override fun onResume() {
        super.onResume()
        refreshData()
    }


    fun refreshData() {
        user = ACache.get(this).getAsObject("user") as User
        tv_nickname.setText(user!!.nickName)
        im_gender.setImageResource(if (user!!.gender === 0) R.mipmap.sex_man else R.mipmap.sex_female)
    }

}
